package flights.db;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import redis.clients.jedis.Jedis;


/* This class is responsible to connect to the database 
 * and evey other class which use the DB should get an handle
 * to the connection using this class.
 * IT HAS ONLY STATIC MEMEBRS 
 */
public class RedisConn
{
	static Jedis conn;
	  // private DataSource dataSource;
	   //private JdbcTemplate jdbcTemplateObject;
	   
	private static void initConn() throws ClassNotFoundException, JSONException
	{
		System.out.println("Loading the driver...");
        Class.forName("redis.clients.jedis.Jedis");
        System.out.println("Loading successed  ---------------");
        
        String jsonEnvVars = java.lang.System.getenv("VCAP_SERVICES");
        if(jsonEnvVars != null){
			parseUrlFromEnvVarsAndConnect(jsonEnvVars);
		}
		else{
			conn= new Jedis("localhost");
		}

        System.out.println((new StringBuilder("conn successed. conn=")).append(conn).toString());
    }
	
    private static void parseUrlFromEnvVarsAndConnect(String jsonEnvVars) throws JSONException {
		JSONObject jsonObject = new JSONObject(jsonEnvVars);
		JSONArray jsonArray = jsonObject.getJSONArray("redis-2.2");
		jsonObject = jsonArray.getJSONObject(0);
		jsonObject = jsonObject.getJSONObject("credentials");
		String host 	=  jsonObject.getString("host");
		System.out.println("parseUrlFromEnvVarsAndConnect host="+host);
		String port 	=  jsonObject.getString("port");
		System.out.println("parseUrlFromEnvVarsAndConnect port="+port);
		String dbName 	=  jsonObject.getString("name");
		System.out.println("parseUrlFromEnvVarsAndConnect dbName="+dbName);
		String password =  jsonObject.getString("password");
		
		System.out.println("parseUrlFromEnvVarsAndConnect password="+password);
		conn = new Jedis(host, Integer.parseInt(port));
		conn.auth(password);
	}
    
    public static Jedis getConnection() throws ClassNotFoundException, JSONException
    {
    	conn = null;
    	if (conn == null)
    	{
    		initConn();
    	}
    	
    	return conn;
    }

}
